package com.sk.bilibili.view.fragment.main.home;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.sk.bilibili.R;
import com.sk.bilibili.adapter.vlayout.main.channel.ChannelAdapter;
import com.sk.bilibili.adapter.vlayout.main.channel.HeaderAdapter;
import com.sk.bilibili.adapter.vlayout.main.channel.TitleAdapter;
import com.sk.bilibili.adapter.vlayout.main.channel.TypeAdapter;
import com.sk.bilibili.bean.Member;
import com.sk.bilibili.bean.Type;
import com.sk.bilibili.databinding.FragmentMainChannelBinding;
import com.sk.bilibili.event.MainMenuEvent;
import com.sk.bilibili.model.fragment.main.home.ChannelModel;
import com.sk.bilibili.utils.DataUtils;
import com.sk.bilibili.view.activity.ChannelActivity;
import com.sk.bilibili.view.fragment.BaseFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ChannelFragment extends BaseFragment<FragmentMainChannelBinding, ChannelModel> implements SwipeRefreshLayout.OnRefreshListener {

    @Override
    protected void afterSetView() {
        initHeader();
        initBody();
    }

    private void initBody() {
        initView();
        bindEvent();
        onRefresh();
    }

    private void bindEvent() {
        bind.srlShow.setOnRefreshListener(this);
    }

    private TypeAdapter typeAdapter;
    private ChannelAdapter channelAdapter;

    private void initView() {
        bind.srlShow.setColorSchemeResources(R.color.pink);
        VirtualLayoutManager manager = new VirtualLayoutManager(getContext());
        bind.rvShow.setLayoutManager(manager);
        DelegateAdapter adapter = new DelegateAdapter(manager);
        adapter.addAdapter(new HeaderAdapter(getContext(), this));
        typeAdapter = new TypeAdapter(getContext(), this);
        adapter.addAdapter(typeAdapter);
        adapter.addAdapter(new TitleAdapter(getContext(),"我最近看过这些频道的视频"));
        channelAdapter = new ChannelAdapter(getContext(), this);
        adapter.addAdapter(channelAdapter);
        bind.rvShow.setAdapter(adapter);
    }

    private void initHeader() {
        model.loadMember();
        bind.avAvatar.setOnClickListener(v -> EventBus.getDefault().post(MainMenuEvent.closeEvent()));
    }

    @Override
    public void onRefresh() {
        model.loadData();
        channelAdapter.setData(Arrays.asList("1"));
    }

    public void onTypeClick(int pos) {
        toast("频道类型:"+pos);
    }

    public void onChannelClick(int pos) {
        ChannelActivity.start(getContext(),pos);
    }

    public void loadTypeSuccess(List<Type> types) {
        typeAdapter.setData(types);
        bind.srlShow.setRefreshing(false);
    }

    public void loadMemberSuccess(Member member) {
        bind.avAvatar.setRes(member.getAvatar(),member.getExtra().getPendant());
    }

}